<?
/**
 * This file is part of XNAT light.
 *
 * XNAT light is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * XNAT light is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with XNAT light.  If not, see <http://www.gnu.org/licenses/>.
 */
namespace NRG\Framework\Controllers;

use NRG\Framework\Common\Registry as Registry;
use NRG\Framework\Exceptions\IllegalArgumentException as IllegalArgumentException;
use NRG\Database\Mappers as Mappers;

/**
 * Genetics controller
 *
 * @package NRG\Framework\Controllers
 */
class Genetics extends BaseController
{
    /**
     * XNAT object
     * 
     * @var Xnat 
     */
    protected $_xnat;

    /**
     * Pre-dispatch of action
     */
    public function preDispatch()
    {
        $this->_xnat = Registry::get("xnat");
    }

    /**
     * Index action
     */
    public function indexAction()
    {
        if($this->_session->getMethod() == "post")
            $this->insertNewData();
    }

    /**
     * Insert new data
     */
    protected function insertNewData()
    {
        $this->adminOnly();

        // what does the user want to do
        $do_insert = $this->_session->hasPostParam("insert");
        $do_update = $this->_session->hasPostParam("update");

        // check for POST CSV file
        if($file = $this->_session->getFileByName("map.csv"))
            $h = fopen($file, "r+");
        else if($file = $this->_session->getFileByKey("csv"))
            $h = fopen($file, "r+");
        else
        {
            // ERROR no file found
            $this->_view->vals = array("error" => true, "message" => "post file with key 'csv' or filename 'map.csv'");
            return;
        }

        // ERROR file not readable   
        if($h === FALSE)
        {
            $this->_view->vals = array("error" => true, "message" => "file could not be opened");
            return;
        }
        
        // read CSV file
        $csv = Array();
        while(($row = fgetcsv($h, 0, ",")) !== FALSE)
        {
            if(count($row) != 2)
            {
                // ERROR invalid CSV
                $this->_view->vals = array("error" => true, "message" => "each row of CSV must contain only 2 columns");
                return;
            }
           
            $label = trim($row[0]);
            $famid = trim($row[1]);
            $csv[$label] = $famid;
        }
        fclose($h);
        
        if(count($csv) == 0)
        {
            // ERROR file is empty
            $this->_view->vals = array("message" => "csv is empty");
            return;
        }

        // get all MR Sessions with Family IDs
        $result = $this->_xnat->query("SELECT xnat_imagesessiondata.id,label,famid FROM xnat_imagesessiondata JOIN xnat_experimentdata ON (xnat_imagesessiondata.id=xnat_experimentdata.id)");

        $xnat_data = array();
        foreach($result as $row)
        {
            $label = trim($row["label"]);
            $id = trim($row["id"]);
            $famid = trim($row["famid"]);

            if(array_key_exists($label, $allfamids))
            {
                // ERROR multiple of same label in database
                $this->_view->vals = array("error" => true, "message" => "found redundant label in database '$label'");
                return;
            }

            $xnat_data[$label] = $famid;
            $label_id_map[$label] = $id;
        }
        
        // check for MR Sessions with existing famid
        $insert = array();
        $update = array();
        $duplicate = array();
        $missing = array();
        foreach($csv as $label=>$famid)
        {
            if(! array_key_exists($label, $xnat_data))
                $missing[] = $label;
            elseif($xnat_data[$label] == "")
                $insert[] = $label;
            elseif($xnat_data[$label] == $famid)
                $duplicate[] = $label;
            elseif($xnat_data[$label] != $famid)
                $update[] = $label;
        }
        
        $this->_view->vals = array("insert" => $insert, "update" => $update, "duplicate" => $duplicate, "missing" => $missing);
       
        // do actual insert 
        if($do_insert)
        {
            $this->_view->vals["do_insert"] = true;

            foreach($insert as $label)
            {
                $insert_famid = $csv[$label];
                $id = $label_id_map[$label];
                $this->_xnat->query("UPDATE xnat_imagesessiondata SET famid=$1 WHERE id=$2", array($insert_famid, $id));
            }
        }

        // do actual update
        if($do_update)
        {
            $this->_view->vals["do_update"] = true;
            
            foreach($update as $label)
            {
                $update_famid = $csv[$label];
                $id = $label_id_map[$label];
                
                //$this->_xnat->query("UPDATE xnat_imagesessiondata SET famid=$1 WHERE id=$2", array($update_famid, $id));
            }
        }
    }
} 
